﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.EntityClient;
using System.Data.Linq;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using QuaManSys;

namespace QuaManSys.InnerInfo
{

    public partial class InnerInfoRegist : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) 
            {
                Tab_Person user = (Tab_Person)Session["CurUser"];
                txtInfoWrt.Text = user.name;
                txtInfoDep.Text = user.department;
                txtWrtDat.Text = DateTime.Now.ToShortDateString();
                GetProjectNumbers(); 
            }
            string s= maxID();
            lblNo.Text=AutoCreatID("HHM",s);
            //using(var db=new QuaManSysEntities())
            //{   
            //    var InnerQualityInfo1 = new InnerQualityInfo { qualityInfoId = lblNo.Text };
            //    db.InnerQualityInfo.Add(InnerQualityInfo1);
            //    db.SaveChanges();

            //}

        }


      
      

        /// <summary>
        /// 将工程编号和后台数据库绑定
        /// </summary>

        private void GetProjectNumbers()
        {
            using (var context = new QuaManSysEntities())
            {
                try
                {

                    ListItem initLi = new ListItem("--请选择--");
                    ddlProNo.Items.Insert(0, initLi);
                    int count = 1;
                    foreach (var item in context.Tab_ProjectNo)
                    {
                        ListItem li = new ListItem(item.projectNo);
                        ddlProNo.Items.Insert(count++, li);
                    }
                }
                catch (EntitySqlException ex)
                {
                    Console.WriteLine(ex.ToString());
                }

            }
        }

        private void AutoFillProjectRel()
        {

            using (var context = new QuaManSysEntities())
            {
                try
                {
                    var result = from c in context.Tab_ProjectNo
                                 where ddlProNo.Text == c.projectNo
                                 select new { c.machinemodelNo, c.machineNo };
                    txtMacTyp.Text = result.First().machinemodelNo;
                    txtMacNo.Text = result.First().machineNo;
                }
                catch (EntitySqlException ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
        /// <summary>
        /// 自动显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlProNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            AutoFillProjectRel();
        }

        //private void QueryDepartment()
        //{
        //    //using (var edm = new QuaManSysEntitiesMain())
        //    //{
        //    //    ObjectQuery<Tab_Department> departments = edm.Tab_Department;
        //    //    IQueryable<Tab_Department> department = from c in departments
        //    //                                            select c;

        //    //}
        //}



        //private string getDate()
        //{
        //    string date = DateTime.Now.Date.ToShortDateString();
        //    return date;
        //}




        /// <summary>
        /// 提交到数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnInfoSub_Click(object sender, EventArgs e)
        {
            string infoCat = "";
            if (CheckBox1.Checked) infoCat = "已处理（需后继关注）";
            if (CheckBox2.Checked) infoCat = "未处理（需跟踪处理）";



            InnerQualityInfo insertInner = new InnerQualityInfo
            {
                qualityInfoId = lblNo.Text,
                projectNo = ddlProNo.Text,
                components = txtComponent.Text,
                producer = txtManufac.Text,
                faultType = txtFaiTyp.Text,
                projectCategory = infoCat,
                name = txtPjNam.Text,
                deadline = Convert.ToDateTime(txtProDL.Text),
                customerLinker = txtCustomer.Text,
                telephone = txtCusTel.Text,
                specialDemands = txtSpeReq.Text,
                informationSource = DDLInfoCla.Text,
                levelOfImportance = DDLImpLev.Text,
                description = txtInfoDsc.Text,
                registrantName = txtInfoWrt.Text,
                registrantDepart = txtInfoDep.Text,
                //registDate = Convert.ToDateTime(txtWrtDat.Text),
                registDate = DateTime.Now.Date,
                recommendedTreatPlan = txtReqAdv.Text,
                processingStatus = "分发",
                processingResults = txtReqRsl.Text,
                processingAssess = txtProCmm.Text,
                informationCategory = txtPjCls.Text
            };
            InnerResponsibleDepart resDept = new InnerResponsibleDepart
            {
                department = DDLDepRes.Text,
                qualityInfoId = lblNo.Text,
                isResponDepart = 1
            };

            InnerResponsibleDepart dept = new InnerResponsibleDepart
            {
                department = DDLDepFoc.Text,
                qualityInfoId = lblNo.Text,
                isResponDepart = 0
            };
    
            using (var db = new QuaManSysEntities())
            {   
                db.InnerQualityInfo.Add(insertInner);
                db.SaveChanges();
                db.InnerResponsibleDepart.Add(resDept);
                db.SaveChanges();
                db.InnerResponsibleDepart.Add(dept);
                db.SaveChanges();
            }
        }


        //private string GetInnerQuaNumber()
        //{
        //    string preNumber = "HHM";
        //    string year = DateTime.Now.Year.ToString();
        //    string number = GetNextNumber();
        //    number = preNumber + year + number;
        //    return number;
        //}

       
        /// <summary>
        /// 找最大的自动生成单号
        /// </summary>
        public static string maxID()
        {
            var context = new QuaManSysEntities();

            if (context.InnerQualityInfo.Count() == 0)
            {
                return "";

            }
            else
            {
                var query = from b in context.InnerQualityInfo
                            orderby b.qualityInfoId
                            select b.qualityInfoId;
                return query.Max();

            }



        }

        /// <summary>
        /// 生成自动编号
        /// </summary>
        /// <param name="flag"></param>
        /// <param name="TableName"></param>
        /// <param name="FieldName"></param>
        /// <returns></returns>
        public static string AutoCreatID(string flag, string maxID)
        {
            string dbDateTime = DateTime.Now.Year.ToString();
            //string Str = "select max(" + FieldName + ") id from " + TableName;//查询表中的字段
            //object obj = Datasource.DbHelperSQL.GetSingle(Str);//把查询字符串Str放到GetSingle()中执行查询(Command)并返回查询结果（对象）
            //string maxID = "";
            //if (obj != null)//返回（查询字符串）对象
            //    maxID = Datasource.DbHelperSQL.GetSingle(Str).ToString();
            string Result = "";
            if (maxID == "")//没有最大编号
            {
                Result = flag + DateTime.Now.Year + "001";//HHM2012001
            }
            else
            {
                //截取字符
                string strFirstFour = maxID.Substring(3, 4);
                string strLastThree = maxID.Substring(7, 3);
                if (dbDateTime == strFirstFour)//截取的最大编号（20090225）是否和数据库服务器系统时间相等
                {
                    string strNewThree = (Convert.ToInt32(strLastThree) + 1).ToString("000");//0000+1
                    Result = flag + DateTime.Now.Year + strNewThree;//HHM2012001
                }
                else
                {
                    Result = flag + DateTime.Now.Year + "001";
                }
            }
            return Result;
        }





    }
}
